#-------------------------------------------------------------------------------
# Name:        zip_to_pdf_converter.py
# Purpose:     Classes to extract PDF from LibreOffice plugin-generated ZIP file
#
# Authors:     John Graves <john.graves@slidespeech.com>
#
# Copyright:   (c) Slidespeech Ltd 2012
# Licence:     MIT license
#-------------------------------------------------------------------------------

import os, sys
from converter import Converter
from zipfile import ZipFile

class ZipToPDFConverter(Converter):
    def __init__(self, zipFile, pdfPath=None, previous=None):
        Converter.__init__(self, previous)
        self._zipFile = zipFile
        if pdfPath is None:
            self._pdfPath = self.tempDir()
        else:
            self._pdfPath = pdfPath
        self._tempDir = self._pdfPath
        self._pdfFile = 'contents.pdf'

    def _convertImpl(self):
        """Extracts the PDF file
        CONTENTS/contents.pdf
        from the given ZIP file to indicated path"""
        try:
            zip = ZipFile(self._zipFile,'r')
            f = zip.extract(u"CONTENTS/contents.pdf", self._pdfPath)

        except Exception as ex:
            raise RuntimeError("Could not extract CONTENTS/contents.pdf " + \
                               "from ZIP file {0} to path {1}".format(self._zipFile, self._pdfPath))

        self._pdfPath = os.path.join(self._pdfPath,'CONTENTS')

    def pdfPath(self):
        return self._pdfPath

    def pdfFile(self):
        return self._pdfFile

if __name__ == "__main__":
    # a simple test/demo
    # into CONTENTS
#    c = ZipToPDFConverter(sys.argv[1], os.getcwd())
    # into tmp\CONTENTS
    c = ZipToPDFConverter(sys.argv[1])
    c.convert()
    print("PDF Path: {0}".format(c.pdfPath()))
    print("PDF File: {0}".format(c.pdfFile()))